package com.xxjqr.rbac.aop;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.xxjqr.rbac.anno.OperateLog;
import com.xxjqr.rbac.auth.JwtUser;
import com.xxjqr.rbac.entity.pojo.TbOperLog;
import com.xxjqr.rbac.enums.BusinessStatusEnum;
import com.xxjqr.rbac.task.AsyncTask;
import com.xxjqr.rbac.util.AddressUtil;
import com.xxjqr.rbac.util.IpUtil;
import com.xxjqr.rbac.util.ServletUtil;
import com.xxjqr.rbac.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.*;

@Aspect
@Component
@Slf4j
public class LogAspect {

    // 配置织入点
    @Pointcut("@annotation(com.xxjqr.rbac.anno.OperateLog)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
        try {
            // 获得方法上的注解
            OperateLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // *========数据库日志=========*//
            TbOperLog operLog = new TbOperLog();
            operLog.setStatus(BusinessStatusEnum.SUCCESS);
            // 请求的ip和地址
            String ip = IpUtil.getIpAddr(ServletUtil.getRequest());
            operLog.setOperIp(ip);
            operLog.setOperAddr(AddressUtil.getRealAddressByIP(ip));
            // 返回结果,isPrimitive可以判断是否是基本类型或void；该aop是在接口返回数据到前端前执行的，所以还没有进行Response包装，所以基本类型没有办法使用JOSN格式化
            if (jsonResult!=null){
                if (jsonResult.getClass().isPrimitive()) {
                    operLog.setJsonResult(jsonResult.toString());
                } else {
                    String result = JSON.toJSONString(jsonResult);
                    //operLog.setJsonResult(result.length() > 2000 ? result.substring(0, 2000) : result);
                    operLog.setJsonResult(result);
                }
            }
            //请求url
            operLog.setRequestUrl(ServletUtil.getRequest().getRequestURI());
            //获取用户信息 1 从security上下中获取，2 解析token获取
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication != null) {
                JwtUser jwtUser = (JwtUser)authentication.getPrincipal();
                if (jwtUser != null) {
                    operLog.setOperName(jwtUser.getUsername());
                }
            }


            if (e != null) {
                operLog.setStatus(BusinessStatusEnum.FAIL);
                String message = Arrays.toString(e.getStackTrace());
                operLog.setErrorMsg(message);
                //if (message.length() > 2000) {
                //    operLog.setErrorMsg(message.substring(0, 2000));
                //} else {
                //    operLog.setErrorMsg(message);
                //}
            }

            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(ServletUtil.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, controllerLog, operLog);
            // 保存数据库

            AsyncTask asyncTask = SpringUtil.getBean("asyncTask");
            asyncTask.insertOperLog(operLog);
            //AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * @param log     日志
     * @param operLog 操作日志
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, OperateLog log, TbOperLog operLog) {
        // 设置action动作
        operLog.setOperType(log.operType());
        // 设置标题
        operLog.setTitle(log.title());
        // 设置操作人类别
        operLog.setOperatorType(log.operatorType());
        // 是否需要保存request，参数和值
        if (log.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operLog);
        }
    }

    /**
     * 获取请求的参数，放到log中
     * @param operLog 操作日志
     */
    private void setRequestValue(JoinPoint joinPoint, TbOperLog operLog) {
        String requestMethod = operLog.getRequestMethod();
        Signature signature = joinPoint.getSignature();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operLog.setOperParam(params);
        } else {
            String[] parameterNames = ((MethodSignature) signature).getParameterNames();
            int length = parameterNames.length;
            Object[] args = joinPoint.getArgs();
            Map<String, Object> paramsMap = new HashMap<>();
            for (int i = 0; i < length; i++) {
                if (!Objects.isNull(args[i])) {
                    if ((args[i] instanceof String)) {
                        if (!StrUtil.isEmpty((String) args[i])) {
                            paramsMap.put(parameterNames[i], args[i]);
                        }
                    } else {
                        paramsMap.put(parameterNames[i], args[i]);
                    }
                }
            }
            //Map<?, ?> paramsMap = (Map<?, ?>) ServletUtil.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operLog.setOperParam(JSON.toJSONString(paramsMap));
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private OperateLog getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(OperateLog.class);
        }
        return null;
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        StringBuilder params = new StringBuilder();
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!isFilterObject(o)) {
                    Object jsonObj = JSON.toJSON(o);
                    params.append(jsonObj.toString()).append(" ");
                }
            }
        }
        return params.toString().trim();
    }

    /**
     * 判断是否是需要过滤的对象。主要是过滤文件上传
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
